<template>
    <div>
      <!--添加角色-->
        <el-button type="primary" @click="addRoles">添加角色</el-button>
       <el-dialog title="添加新角色" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="ruleForm.name" ref="addRolesName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="describe">
                <el-input v-model="ruleForm.describe"  ref="addRolesDes"></el-input>
              </el-form-item>
              </el-form>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="subRoles('ruleForm')">确 定</el-button>
          </span>
      </el-dialog>
      <!--编辑角色-->
      <el-dialog title="编辑角色" :visible.sync="dialogEdit" width="30%" :before-close="handleClose">
          <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
           <el-form-item label="角色名称" prop="name">
                <el-input v-model="editForm.name" ref="addRolesName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="describe">
                <el-input v-model="editForm.describe"  ref="addRolesDes"></el-input>
          </el-form-item>
             </el-form>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogEdit = false">取 消</el-button>
            <el-button type="primary" @click="subEdit('editForm')">确 定</el-button>
          </span>
      </el-dialog>
      <!--分配权限-->
      <el-dialog title="分配权限" :visible.sync="diaAssing" width="50%" :before-close="handleClose">
       <el-tree 
       :data="treeList" show-checkbox 
       node-key="id" default-expand-all 
       :props="defaultProps" 
       @check="checked"
       :default-checked-keys="key">
      </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="diaAssing = false">取 消</el-button>
          <el-button type="primary" @click="subAss">确 定</el-button>
        </span>
    </el-dialog>
    <!--表格-->
    <el-table class="addRoleList" :data="rolesList" :stripe="true" border style="width: 100%">
      <el-table-column type="expand" label="" style="margin-bottom:10px" width="50">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand" >
            <table class="branch">
              <tr v-for="item,i in scope.row.children" :key="item.index">
                <td class="td_l">
                  <el-tag  closable type="" @close="close(i,scope.row.children,scope.row,item)" >{{item .authName}}</el-tag>
                </td>
                <td class="td_r">
                <ul>
                  <li v-for="opt,i in item.children" :key="item.index">
                    <div class="left">
                        <el-tag closable type="success" @close="close(i,item.children,scope.row,opt)">{{opt.authName}}</el-tag>
                    </div>
                    <div class="right">
                      <el-tag closable type="warning" 
                      v-for="item,i in opt.children" 
                      :disable-transitions="true"
                      :key="item.index" 
                      @close="close(i,opt.children,scope.row,item)">{{item.authName}}</el-tag>
                    </div>
                  </li>
                </ul>
              </td>
            </tr>
         </table>
      </el-form-item>
    </el-form>  
  </template>
</el-table-column>
    <el-table-column prop="index" label="#" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="200">
    </el-table-column>
      <el-table-column  prop="roleDesc" label="职位描述" width="450">
    </el-table-column>
    <el-table-column label="操作" width="300">
      <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row)">编辑</el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRoles(scope.row)">删除</el-button>
        <el-button type="warning" icon="el-icon-setting" size="mini" @click="assign(scope.row)">分配权限</el-button>
      </template>
    </el-table-column>
</el-table>
</div>
</template>

<script>

export default {
    data() {
      return {
        rolesList:[], //角色列表
        dialogVisible:false,
        dialogEdit:false,
        diaAssing:false,
        key:[], //存储修改权限的时候树形菜单默认选中的key值
        treeList:[],  //树形列表
        defaultProps: {   //树形列表的数据设置
          children: 'children',
          label: 'authName'
        },
         ruleForm: {
          name: '',
           describe:""
         },
         editForm:{
           id:-1,
           name:"",
          describe:""
         },
         subAssForm:{
          id:-1,
          node:[]
         },
       rules: {
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
            { min: 2, max: 5, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          describe: [
            { required: true, message: '请输入角色描述', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ]
         }
      }
    },
    //获取角色列表
    methods:{
      getRolesList(){
        this.$http.get("roles",{headers:{'Authorization':localStorage.getItem("token")}}).then(res=>{
          if(res.body.meta.status == 200){
              this.rolesList = res.body.data
             //给得到的数据每一项添加一个index值一边渲染列表的时候需要
              this.rolesList.forEach((item,i)=>{
                item.index = i+1
              })
          //console.log( this.rolesList)
            }
          })
      },
      close(idx,opt,row,item){
        this.$http.delete("roles/"+row.id+"/rights/"+item.id,
         {headers:{'Authorization':localStorage.getItem('token')}})
         .then(res=>{
          if(res.body.meta.status == 200){
             opt.splice(idx,1)
          }
         })
      },
        //点击添加角色的按钮
        addRoles(){
          this.dialogVisible = true
         },
        //提交添加的角色
        subRoles(ruleForm){
          this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.dialogVisible = false
            let name = this.$refs.addRolesName.value;
            let des = this.$refs.addRolesDes.value;
            this.$http.post("roles",{roleName:name,roleDesc:des},
            { headers:{"Authorization":localStorage.getItem("token")} })
            .then(res=>{
              if(res.body.meta.status == 201){
                  this.rolesList.push({
                   children:[],
                   roleDesc:res.body.data.roleDesc,
                   roleName:res.body.data.roleName,
                   id:res.body.data.roleId
                 })
                  this.rolesList.forEach((item,i)=>{
                    item.index = i+1
                  })
                   this.$message({
                    message: '添加角色成功',
                    type: 'success'
                  });
                 // console.log(res.body)
              }
              else{
                this.$message.error('添加角色失败');
              }
            })
          }  
          else {
            return false;
          }
        });
         
        },
        //点击编辑角色的按钮
        editRoles(row){
          this.dialogEdit = true;
          this.editForm.name = row.roleName;
          this.editForm.describe = row.roleDesc || "";
          this.editForm.id = row.id
        },
        //提交编辑之后的角色信息到后台
        subEdit(editForm){
          this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.dialogEdit = false
            this.$http.put("roles/"+ this.editForm.id,
            { roleName: this.editForm.name,roleDesc: this.editForm.describe },
            { headers:{"Authorization":localStorage.getItem("token")} }
            ).then(res=>{
            if(res.body.meta.status == 200){
               //console.log(res.body)
               this.rolesList.forEach(item=>{
                  if(item.id == res.body.data.roleId){
                      item.roleName = res.body.data.roleName;
                      item.roleDesc = res.body.data.roleDesc
                  }
               })
                this.$message({
                message: '修改角色成功信息',
                type: 'success'
            });
          }
        })
          } 
          else {
              return false;
            }
        });
      },
       //点击删除角色
       delRoles(row){
          this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
             this.$http.delete("roles/"+row.id,{headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
                this.getRolesList()
                this.$message({
                type: 'success',
                message: '删除成功!'
                });
            })
          }
        ).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
       },
      //点击分配权限的按钮获取权限列表
      assign(row){
        this.key = []
        this.getChidren(row.children)
        this.diaAssing = true;
        this.subAssForm.id = row.id
        this.$http.get("rights/tree",{headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
          if(res.body.meta.status == 200){
            this.treeList = res.body.data
          }
        })
      },
      //获取每一列的权限数据将权限id存在key里面
      //只获取最里面一层数据的id
      getChidren(data){
        data.forEach((item,i)=>{
          item.children.forEach(item=>{
             item.children.forEach(item=>{
               this.key.push(item.id)
             })
           })
        })
      },
      //得到权限树形列表点击的值
   checked(node,data){
     this.subAssForm.node=data.checkedKeys
    },
      //提交修改权限之后的数据
     subAss(){
        this.diaAssing = false;
        let rids = this.subAssForm.node.join(",")
        this.$http.post("roles/"+ this.subAssForm.id+"/rights", {rids: rids},
        { headers:{"Authorization":localStorage.getItem("token")}})
        .then(res=>{
         if(res.body.meta.status == 200){
             this.$message({
                type: 'success',
                message: '更新权限成功!'
              });
            this.getRolesList()
            this.key=[]
         }
          else{
              this.$message.error('更新角色失败');
          }
        })  
      },
         handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
       }
    },
    created(){
       this.getRolesList()
       this.$store.commit("changeTitle",{"t1":"权限管理","t2":"角色管理"})
    },
    
}
</script>

 <style lang="scss" scoped>
.addRoleList{
    margin-top: 20px;
    .branch{
      width: 100%;
      ul{
        list-style: none;
        margin: 0;
        padding: 0
      }
      tr{
        display: flex;
       
      }
      .td_l{
        flex: 1;
        display: flex;
        align-items: center;
       justify-content: flex-end;
       padding-right: 20px
        }
      .td_r{
        padding: 20px;
        flex: 7;
          li{
          display: flex;
          margin-top:20px;
          .left{
            flex: 2
            }
          .right{
            flex:8;
           border-bottom: 1px solid #eee;
          .el-tag{
            margin-right: 40px;
            margin-bottom: 30px
          }
          }
        }
      }
     
    }
}
</style>